package de.ret_world.openrpgstudio.eventengine.scripts;

import de.ret_world.openrpgstudio.editor.Database;
import de.ret_world.openrpgstudio.editor.Project;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.TwoArgFunction;

/**
 *  The Event Lua Library for working with Events through Lua code.
 * 
 * @author Emu
 */
public class EventLib extends TwoArgFunction {

    @Override
    public LuaValue call(LuaValue arg1, LuaValue arg2) {
        Database database = Project.getInstance().getDatabase();
        switch (opcode) {
            case 0: {
                LuaValue t = tableOf();
                this.bind(t, EventLib.class, new String[]{"newEvent", "changeEvent", "getEvent"}, 1);
                env.set("Events", t);
                return t;
            }
            case 1: //newEvent
                if (arg1.istable()) {
                    Event e = new Event();
                    e.create(arg1);
                    database.putScriptObject(Event.TYPE, e.getID(), e);
                } else {
                    return error("no table: " + arg1);
                }
                return NIL;
            case 2: //changeEvent
                if (arg1.isstring()) {
                    Event e = (Event) database.getScriptObject(Event.TYPE, arg1.toString());
                    if (e == null) {
                        return error("no such Event found unter: " + arg1);
                    }
                    if (arg2.istable()) {
                        e.create(arg2);
                    } else {
                        return error("no table: " + arg2);
                    }
                } else {
                    return error("no string: " + arg1);
                }
                return NIL;
            case 3: //ngetEvent
                if (arg1.isstring()) {
                    Event e = (Event) database.getScriptObject(Event.TYPE, arg1.toString());
                    if (e == null) {
                        return error("no such Event found unter: " + arg1);
                    } else {
                        return e.toLua();
                    }
                }
                return NIL;
            default:
                return error("bad opcode: " + opcode);
        }
    }  
}
